package com.yonyou.pmclouds.procedure.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.BuziExCodeConst;
import com.yonyou.pmclouds.procedure.entity.ProcedureVO;
import com.yonyou.pmclouds.procedure.mapper.ProcedureMapper;
import org.apache.commons.lang3.StringUtils;

public class ProcedureUpNameAndCodeCheck implements SingleProcessor<ProcedureVO> {

    private ProcedureMapper mapper;

    public ProcedureUpNameAndCodeCheck(ProcedureMapper mapper) {
        this.mapper = mapper;
    }
    @Override
    public void process(ProcedureVO vo, ProcedureVO orig) throws BusinessException {
        if (StringUtils.equals(vo.getSname(), orig.getSname()) && StringUtils.equals(vo.getScode(),orig.getScode())) {
            return;
        }

        boolean codeUnique = mapper.countCode(vo.getPkTenant(), vo.getScode()) == 0;
        boolean nameUnique = mapper.countName(vo.getPkTenant(), vo.getSname()) == 0;
        if (StringUtils.equals(vo.getSname(), orig.getSname())) {
            //只校验编码
            if (!codeUnique) {
                throw new BusinessException("已经存在相同的工序编码，请修改!", BuziExCodeConst.CODE_CODE_DUPLICATE);
            }
        }

        if (StringUtils.equals(vo.getScode(), orig.getScode())) {
            //只校验名字
            if (!nameUnique) {
                throw new BusinessException("已经存在相同的工序名称，请修改!", BuziExCodeConst.CODE_NAME_DUPLICATE);
            }

        }

        if (!codeUnique && !nameUnique) {
            throw new BusinessException("已经存在相同的工序编码、名称，请修改!", BuziExCodeConst.CODE_NAME_CODE_DUPLICATE);//
        }
    }
}
